package com.golxen.framework.netty.session.cross;


import com.golxen.framework.CrossProtocol;
import com.golxen.framework.PBPacket.PBPacket;
import com.golxen.framework.common.server.cross.cmd.CrossCommandWrapper;
import com.golxen.framework.executor.ThreadPlugin;
import com.golxen.framework.netty.NettyServices;
import com.golxen.framework.netty.session.base.ServerLinkedGroup;
import com.golxen.utils.LogUtil;
import com.mysql.cj.util.LogUtils;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;

@ChannelHandler.Sharable
public class CrossServerHandler extends SimpleChannelInboundHandler<PBPacket> {

    protected static Logger logger = LogUtil.COMMON;
    
    private String handlerName;

    public CrossServerHandler() {
        handlerName = "cross";
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        logger.info("receive a connect : " + ctx.channel().remoteAddress());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        logger.info("connection disconnected : " + ctx.channel().remoteAddress());
        ServerLinkedGroup client = ctx.channel().attr(NettyServices.LINKED_CLIENT).get();
        if (client != null) {
            CrossAgentLinkedSet.closeCtxSession(ctx);
            logger.warn(toMessage(
                    "close the connection to agent disconnected. session : " + ctx.channel().remoteAddress()));
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        logger.warn("connect error : " + ctx.channel().remoteAddress() + ", error : " + cause, cause);

        ServerLinkedGroup client = ctx.channel().attr(NettyServices.LINKED_CLIENT).get();
        if (client != null) {
            CrossAgentLinkedSet.closeCtxSession(ctx);
            logger.warn(toMessage("caught exception the connection to agent disconnected. session : "
                    + ctx.channel().remoteAddress()));
        }

        ctx.close();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, PBPacket msg) throws Exception {
        CrossCommandWrapper cmdWrapper = new CrossCommandWrapper(ctx, msg);
        ThreadPlugin.getServerCommandExecutor().execute(cmdWrapper);

    }

    private String toMessage(String msg) {
        return "[" + handlerName + "] " + msg;
    }
}
